<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Rust：网络库的实现思路 - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html" class="active"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="rust-网络库的实现思路"><a class="header" href="#rust-网络库的实现思路">Rust: 网络库的实现思路</a></h1>
<p>作者：<a href="https://www.zhihu.com/people/zhen-yu-jiang-jun-jie-zhan-pao-29">朕与将军解战袍</a></p>
<p>原载：<a href="https://zhuanlan.zhihu.com/p/615308940">https://zhuanlan.zhihu.com/p/615308940</a></p>
<p>这篇文章主要从 <code>Rust</code> 的类型系统的角度出发，提供一种网络库的实现思路。本文可以看作 <code>actix-web</code> 的阅读笔记。</p>
<h3 id="对不同参数的函数和闭包的抽象"><a class="header" href="#对不同参数的函数和闭包的抽象">对不同参数的函数和闭包的抽象</a></h3>
<p>在进入正题之前，我们先看一段来自 <code>actix-web</code> 官方的示例代码:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use actix_web::{web, App, HttpResponse};

async fn index(data: web::Path&lt;(String, String)&gt;) -&gt; &amp;'static str {
    &quot;Welcome!&quot;
}

let app = App::new()
    .route(&quot;/test1&quot;, web::get().to(index))
    .route(&quot;/test2&quot;, web::get().to(|| HttpResponse::MethodNotAllowed()));
<span class="boring">}
</span></code></pre></pre>
<p>可以看到同样是 <code>get().to(..)</code>， 但却可以接受不同参数的函数和闭包。这也引出了我们对不同参数的函数、闭包进行抽象的需求。</p>
<p>我们定义一个 <code>trait</code> 名为 <code>Factory</code>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait Factory&lt;Args, Res&gt; {
    fn call(&amp;self, args: Args) -&gt; Res;
}
<span class="boring">}
</span></code></pre></pre>
<p>然后为实现了 <code>Fn trait</code> 的类型（因为该函数会被调用多次）， 实现 <code>Factory</code>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T, Res&gt; Factory&lt;(), Res&gt; for T
where
    T: Fn() -&gt; Res,
{
    fn call(&amp;self, _args: ()) -&gt; Res {
        (self)()
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>但函数没有参数的时候，类型参数 <code>Args</code> 就为 <code>()</code> 。由于 <code>rust</code> 中缺少 <code>variadic generics</code>，所以当函数有一个或多个参数时， 我们需要将其打包成一个元组，再在调用的时候解包:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T, Arg0, Res&gt; Factory&lt;(Arg0, ), Res&gt; for T
where
    T: Fn(Arg0) -&gt; Res,
{
    fn call(&amp;self, args: (Arg0, )) -&gt; Res {
        (self)(args.0)
    }
}

impl&lt;T, Arg0, Arg1, Res&gt; Factory&lt;(Arg0, Arg1, ), Res&gt; for T
where
    T: Fn(Arg0, Arg1) -&gt; Res,
{
    fn call(&amp;self, args: (Arg0, Arg1, )) -&gt; Res {
        (self)(args.0, args.1)
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>由于有大量重复代码，我们可以通过宏来实现这个过程:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>macro_rules! factory_tuple {( $(($arg: ident, $n: tt)),+ ) =&gt; {
        impl&lt;T, $($arg,)+ Res&gt; Factory&lt;($($arg,)+), Res&gt; for T
            where T: Fn($($arg,)+) -&gt; Res
        {
            fn call(&amp;self, args: ($($arg,)+)) -&gt; Res {
                (self)($(args.$n,)+)
            }
        }
    };
}

// 由于难以在过程宏中得知这是第几次循环, 所以我们以元组的方式指示这个模板参数在元组中的哪一个位置
// 从而实现在调用对函数参数的解包 
factory_tuple!((Arg0, 0));
factory_tuple!((Arg0, 0), (Arg1, 1));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3), (Arg4, 4));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3), (Arg4, 4), (Arg5, 5));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3), (Arg4, 4), (Arg5, 5), (Arg6, 6));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3), (Arg4, 4), (Arg5, 5), (Arg6, 6), (Arg7, 7));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3), (Arg4, 4), (Arg5, 5), (Arg6, 6), (Arg7, 7), (Arg8, 8));
factory_tuple!((Arg0, 0), (Arg1, 1), (Arg2, 2), (Arg3, 3), (Arg4, 4), (Arg5, 5), (Arg6, 6), (Arg7, 7), (Arg8, 8), (Arg9, 9));
<span class="boring">}
</span></code></pre></pre>
<p>至此, 我们完成了对不同参数(0 ~ 10)的函数和闭包的抽象。我们可以为其定义一个包装类 <code>Handler</code>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Handler&lt;F, A, R&gt; {
    f: F,
    _t: PhantomData&lt;(A, R)&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p>其中 <code>A</code> 代表 <code>Args</code>， <code>R</code> 代表 <code>Res</code>，由于 <code>rust</code> 不允许游离的模板参数的存在，我们使用在 <code>Handler</code> 中定一个 <code>PhantomData&lt;(A, R)&gt;</code>。</p>
<p>接着为 <code>Handler</code> 实现一些方法:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;F, A, R&gt; Handler&lt;F, A, R&gt;
where
    F: Factory&lt;A, R&gt;,
{
    pub fn new(f: F) -&gt; Self {
        Handler {
            f,
            _t: PhantomData::default(),
        }
    }

    pub fn call(&amp;self, args: A) -&gt; R {
        self.f.call(args)
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="反序列化"><a class="header" href="#反序列化">反序列化</a></h3>
<p>回到文章开头展示的 <code>actix-web</code> 的示例代码:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use actix_web::{web, App, HttpResponse};

async fn index(data: web::Path&lt;(String, String)&gt;) -&gt; &amp;'static str {
    &quot;Welcome!&quot;
}

let app = App::new()
    .route(&quot;/test1&quot;, web::get().to(index))
    .route(&quot;/test2&quot;, web::get().to(|| HttpResponse::MethodNotAllowed()));
<span class="boring">}
</span></code></pre></pre>
<p>我们看到函数可以接受不同类型的参数，而这些参数一般都是从发送到服务器的请求所携带的数据中得到的。所以我们还需要一个反序列化的 <code>trait</code>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub trait FromPayload: Sized {
    fn from(payload: &amp;mut Payload) -&gt; Result&lt;Self, String&gt;;
}

pub struct Payload {
    data: *const u8,
    len: usize,
}

impl Payload {
    pub fn len(&amp;self) -&gt; usize {
        self.len
    }

    pub fn from_bytes(bytes: &amp;[u8]) -&gt; Self {
        Payload {
            data: bytes.as_ptr(),
            len: bytes.len(),
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>注意到 <code>FromPayload</code> 是受到 <code>Sized</code> 的限制的，因为我们需要将 <code>Result&lt;Self, ...&gt;</code> 作为返回值， 如果 <code>FromPayload</code> 没有受到 <code>Sized</code> 的限制，那么编译器就无法在编译时得知 <code>Self</code> 的大小，也就无法将 <code>Result&lt;Self, ...&gt;</code> 作为返回值。</p>
<p>而 <code>Payload</code> 结构体本质上是对字节流的抽象，因为这只是一个 <code>demo</code>，方便起见，我就使用裸指针。</p>
<p>接着，我们需要为一些基本的类型实现 <code>FromPayload</code>，如:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl FromPayload for i32 {
    fn from(payload: &amp;mut Payload) -&gt; Result&lt;Self, String&gt; {
        let payload_size = payload.len();
        let t_size = std::mem::size_of&lt;i32&gt;();
        if payload_size &gt;= t_size {
            unsafe {
                let t_ptr = payload.data as *const i32;
                payload.data = payload.data.add(t_size);
                Ok(t_ptr.read())
            }
        } else {
            Err(&quot;Failed to extract args from payload&quot;.into())
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>同样的，由于这个过程很繁琐我们可以通过宏实现:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 为所有实现了 BasicType 的类型都实现 FromPayload
impl&lt;T&gt; FromPayload for T 
where T: BasicType
{
    fn from(payload: &amp;mut Payload) -&gt; Result&lt;Self, String&gt; {
        let payload_size = payload.len();

        if payload_size &gt;= T::SIZE {
            unsafe {
                let t_ptr = payload.data as *const T;
                payload.data = payload.data.add(T::SIZE);
                Ok(t_ptr.read())
            }
        } else {
            Err(&quot;Failed to extract args from payload&quot;.into())
        }
    }
}

// BasicType 是一个 marker trait, 主要用于标记哪些类型是 BasicType
// 而之所以 `BasicType: Copy `, 是因为在 `FromPayload` 的实现中我们只是简单地进行字节的赋值
// 所以只有对于能进行 Copy 的类型来说, 上面的才是安全的
trait BasicType: Copy {}
macro_rules! mark_basic_type {
    ($($T: ident),+) =&gt; {$(
        impl BasicType for $T {}
    )+};
}

// 用宏减少重复代码
mark_basic_type!(
    f32, f64,
    i8, i16, i32, i64, isize,
    u8, u16, u32, u64, usize
);
<span class="boring">}
</span></code></pre></pre>
<p>而由于我们的 <code>handler</code> 所接受的参数都要被打包进一个元组里，所以我们也要为不同的元组实现 <code>FromPayload</code> , 只要约束元组中的每一个类型实现 <code>FromPayload</code>，我们就为该元组实现 <code>FromPayload</code>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl FromPayload for () {
    fn from(_payload: &amp;mut Payload) -&gt; Result&lt;Self, String&gt; {
        Ok(())
    }
}

macro_rules! tuple_impl_from_payload {(  $( ( $($T: ident,)+ ) ),+ ) =&gt; 
    {$(
        impl&lt;$($T),+&gt; FromPayload for ($($T,)+) 
        where 
            // 约束元组中的每一个类型都实现 FromPayload
            $($T: FromPayload),+
        {
            #[allow(non_snake_case)]
            fn from(payload: &amp;mut Payload) -&gt; Result&lt;Self, String&gt; {
                $(let $T = $T::from(payload)?;)+
                Ok(($($T,)+))
            }
        }
    )+};
}

tuple_impl_from_payload!(
    (T0, ), 
    (T0, T1, ),
    (T0, T1, T2, ),
    (T0, T1, T2, T3, ),
    (T0, T1, T2, T3, T4, ),
    (T0, T1, T2, T3, T4, T5, ),
    (T0, T1, T2, T3, T4, T5, T6, ),
    (T0, T1, T2, T3, T4, T5, T6, T7, ),
    (T0, T1, T2, T3, T4, T5, T6, T7, T8, ),
    (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, )
);
<span class="boring">}
</span></code></pre></pre>
<p>其中 <code>()</code> 要特别注意, 因为 <code>()</code> 只有一个实例，且为 <code>zero-sized type</code>，所以从字节流一定能得到它。</p>
<p>至此，我们已经可以从字节流中得到函数的参数了。</p>
<h3 id="对不同类型的-handler-进行抽象"><a class="header" href="#对不同类型的-handler-进行抽象">对不同类型的 <code>Handler</code> 进行抽象</a></h3>
<p>让我们再次回到最开始的代码:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>use actix_web::{web, App, HttpResponse};

async fn index(data: web::Path&lt;(String, String)&gt;) -&gt; &amp;'static str {
    &quot;Welcome!&quot;
}

let app = App::new()
    .route(&quot;/test1&quot;, web::get().to(index))
    .route(&quot;/test2&quot;, web::get().to(|| HttpResponse::MethodNotAllowed()));
<span class="boring">}
</span></code></pre></pre>
<p>我们看到在同一个 <code>App</code> 中是能够储存拥有不同参数和返回值的 <code>Handler</code> 的。而回到我们的 <code>Handler</code> 的定义:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Handler&lt;F, A, R&gt; {
    f: F,
    _t: PhantomData&lt;(A, R)&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p>可以看到 <code>Handler</code> 拥有三个类型参数，这也就意味着拥有不同参数、返回值的函数，甚至是同一参数、同一返回值的闭包都会导致 包含其的 <code>Handler</code> 是完全不同的类型。这也就意味着 <code>App</code> 中是不能直接储存这些 <code>Handler</code> 的。这也引出了一个新的需求： 对不同类型的 <code>Handler</code> 进行抽象。</p>
<p>我们来思考一下，<code>App</code> 是怎么样调用这些 <code>Handler</code> 的:</p>
<p>- 服务器接到请求</p>
<p>- 根据请求中包含的 <code>请求方式</code>、 <code>url</code> 等信息找到相应的处理函数</p>
<p>- 根据处理函数的签名从请求携带的数据中反序列化得到函数参数</p>
<p>- 调用函数</p>
<p>可以看到在调用函数之前我们需要通过反序列化得到函数参数，而我们已经通过 <code>FromPayload</code> 实现了对反序列化过程的抽象。 所以 <code>App</code> 主要做的步骤可以写为:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 注意！这只是伪代码
impl App {
    fn handle_request(&amp;self, req: Request) -&gt; Response {
        let handler = match req.ty {
            RequestType::Get =&gt; self.get_handlers.get(&amp;req.path),
            RequestType::Post =&gt; self.post_handlers.get(&amp;req.path),
        };
        let args = &lt;? as FromPayload&gt;::from(req.payload());

        handler.call(args)
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>在上面的代码中，我们发现在 <code>Handler</code> 被调用之前都需要使用 <code>FromPayload</code> 对 <code>req.payload()</code> 进行反序列化， 那么我们可以把这个过程和对 <code>Handler</code> 的调用封装成一个闭包:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 注意！这只是伪代码
impl App {
    fn handle_request(&amp;self, req: Request) -&gt; Response {
        let handler = match req.ty {
            RequestType::Get =&gt; self.get_handlers.get(&amp;req.path),
            RequestType::Post =&gt; self.post_handlers.get(&amp;req.path),
        };
        let process = |payload: Payload| -&gt; Response {
            let args = &lt;? as FromPayload&gt;::from(&amp;mut payload);
            handler.call(args)
        };
        process(req.payload())
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>那么更进一步，在一个函数被加入 <code>App</code> 的时候，我们就可以将其封装成一个闭包, 这样将可以将不类型的 <code>Handler</code> 统一起来了:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// 注意！这只是伪代码
impl App {
    fn get(&amp;mut self, path: Path, h: Handler&lt;F, A, R&gt;) -&gt; &amp;mut self {
        let process = move |payload: Payload| -&gt; Response {
            let args = &lt;? as FromPayload&gt;::from(&amp;mut payload);
            h.call(args)
        };
        self.get_handlers.insert(path, process);

        self
    }
    fn handle_request(&amp;self, req: Request) -&gt; Response {
        let handler = match req.ty {
            RequestType::Get =&gt; self.get_handlers.get(&amp;req.path),
            RequestType::Post =&gt; self.post_handlers.get(&amp;req.path),
        };
        let process = |payload: Payload| {
            let args = &lt;? as FromPayload&gt;::from(&amp;mut payload);
            handler.call(args)
        };
        process(request.payload())
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>剩下还没有解决的问题就是我们如何得知 <code>Handler</code> 的函数参数类型了, 我们可以通过一个包装类实现:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[derive(Debug, Clone, Copy)]
pub enum HttpStatus {
    Success,
    Failed,
}

pub struct BoxedService {
    service: Box&lt;dyn Fn(Payload) -&gt; HttpStatus&gt;,
}

impl BoxedService {
    pub fn from_handler&lt;F, Args, Res&gt;(handler: Handler&lt;F, Args, Res&gt;) -&gt; Self 
    where
        Args: FromPayload + 'static,
        Res: Into&lt;HttpStatus&gt; + 'static,
        F: Factory&lt;Args, Res&gt; + 'static,
    {
        let service = Box::new(move |mut payload| {
            match Args::from(&amp;mut payload) {
                Ok(args) =&gt; handler.call(args).into(),
                Err(msg) =&gt; {
                    println!(&quot;{msg}&quot;);
                    HttpStatus::Failed
                }
            }
        });

        BoxedService { service }
    }

    pub fn handle(&amp;self, payload: Payload) -&gt; impl Into&lt;HttpStatus&gt; {
        (self.service)(payload)
    }
}
<span class="boring">}
</span></code></pre></pre>
<h3 id="最终实现"><a class="header" href="#最终实现">最终实现</a></h3>
<p>有了上面的铺垫，我们就可以实现最终的 <code>Server</code> 类了:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// file: src/request.rs
use std::fmt::Display;

#[derive(Clone, Copy)]
pub enum RequestType {
    Get,
    Post,
}

pub struct Request {
    pub(crate) ty: RequestType,
    pub(crate) path: Path,
    pub(crate) payload: Vec&lt;u8&gt;,
}

impl Request {
    pub fn get(path: impl Into&lt;Path&gt;, payload: Vec&lt;u8&gt;) -&gt; Request {
        Request { ty: RequestType::Get, path: path.into(), payload }
    }

    pub fn post(path: impl Into&lt;Path&gt;, payload: Vec&lt;u8&gt;) -&gt; Request {
        Request { ty: RequestType::Post, path: path.into(), payload }
    }
}
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct Path {
    p: String,
}

impl Display for Path {
    fn fmt(&amp;self, f: &amp;mut std::fmt::Formatter&lt;'_&gt;) -&gt; std::fmt::Result {
        writeln!(f, &quot;{}&quot;, self.p)
    }
}

impl&lt;T&gt; From&lt;T&gt; for Path 
    where T: Into&lt;String&gt;
{
    fn from(value: T) -&gt; Self {
        Path { p: value.into() }
    }
}

// file: src/server.rs
use std::collections::HashMap;

use crate::request::{Request, RequestType};
use crate::service::{BoxedService, HttpStatus, FromPayload, Payload};
use crate::handler::{Factory, Handler};

#[derive(Default)]
pub struct Server {
    get: HashMap&lt;Path, BoxedService&gt;,
    post: HashMap&lt;Path, BoxedService&gt;,
}

impl Server {
    pub fn new() -&gt; Self {
        Self::default()
    }

    pub fn get&lt;P, F, A, R&gt;(&amp;mut self, path: P, f: F) -&gt; &amp;mut Self 
    where
        P: Into&lt;Path&gt;,
        A: FromPayload + 'static,
        R: Into&lt;HttpStatus&gt; + 'static, 
        F: Factory&lt;A, R&gt; + 'static,
    {
        let handler = Handler::new(f);
        self.get.insert(path.into(), BoxedService::from_handler(handler));

        self
    }

    pub fn post&lt;P, F, A, R&gt;(&amp;mut self, path: P, f: F) -&gt; &amp;mut Self 
    where
        P: Into&lt;Path&gt;,
        A: FromPayload + 'static,
        R: Into&lt;HttpStatus&gt; + 'static, 
        F: Factory&lt;A, R&gt; + 'static,
    {
        let handler = Handler::new(f);
        self.post.insert(path.into(), BoxedService::from_handler(handler));

        self
    }

    pub fn handle_request(&amp;self, request: Request) -&gt; Result&lt;HttpStatus, String&gt; {
        let service = match request.ty {
            RequestType::Get =&gt; match self.get.get(&amp;request.path) {
                Some(s) =&gt; s,
                None =&gt; return Err(format!(&quot;missing get handler for path {}&quot;, request.path)), 
            },
            RequestType::Post =&gt; match self.post.get(&amp;request.path) {
                Some(s) =&gt; s,
                None =&gt; return Err(format!(&quot;missing post handler for path {}&quot;, request.path)), 
            },
        };

        let payload = Payload::from_bytes(&amp;request.payload);
        Ok(service.handle(payload).into())
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>至此，我们的 <code>Server</code> 也完成了。</p>
<h3 id="测试"><a class="header" href="#测试">测试</a></h3>
<p>剩下的最后一步，就是测试了:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[cfg(test)]
mod tests {
    use std::io::Write;

    use crate::{server::*, service::HttpStatus, request::Request};

    fn success() -&gt; HttpStatus {
        HttpStatus::Success
    }

    fn query_book(book_no: usize) -&gt; impl Into&lt;HttpStatus&gt; {
        println!(&quot;query book no.{book_no} .&quot;);

        HttpStatus::Success
    }

    fn post_bill(bill_no: usize, price: f32) -&gt; impl Into&lt;HttpStatus&gt; {
        println!(&quot;bill_no: {bill_no} price: {price}&quot;);

        HttpStatus::Success
    }

    #[test]
    fn it_works() {
        let mut server = Server::new();

        server
            .get(&quot;/&quot;, success)
            .get(&quot;/book&quot;, query_book)
            .post(&quot;/bill&quot;, post_bill);

        let requests = {
            let req1 = Request::get(&quot;/&quot;, vec![]);
            let req2 = Request::get(&quot;/book&quot;, 10usize.to_le_bytes().into());
            let req3 = {
                let mut buf = vec![];
                buf.write(&amp;20usize.to_le_bytes()).unwrap();
                buf.write(&amp;1.2f32.to_le_bytes()).unwrap();
                Request::post(&quot;/bill&quot;, buf)
            };
            let err_request1 = Request::get(&quot;/404&quot;, vec![]);
            let err_request2 = Request::post(&quot;/404&quot;, vec![]);

            [req1, req2, req3, err_request1, err_request2]
        };

        for request in requests {
            let res = server.handle_request(request);
            println!(&quot;{res:?}&quot;);
        }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>输出:</p>
<pre><code class="language-text">Ok(Success)
query book no.10 .
Ok(Success)
bill_no: 20 price: 1.2
Ok(Success)
Err(&quot;missing get handler for path /404\n&quot;)
Err(&quot;missing post handler for path /404\n&quot;)
</code></pre>
<h3 id="总结"><a class="header" href="#总结">总结</a></h3>
<p>我个人认为这种模式不只是适用于网络库的构建，像 <code>bevy</code> 的 <code>ecs</code> 系统也可以用类似的方法实现。</p>
<p>完整的代码请移步github仓库:</p>
<p>https://github.com/a1393323447/server-in-rust</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
